<template>
  <div class="course">
    <!-- 搜索部分 -->
    <el-row :gutter="10" class="search-section">
      <el-col :span="6">
        <el-form-item label="会议名称：">
          <el-input v-model="filters.name" placeholder="请输入会议名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="作者：">
          <el-input v-model="filters.creator" placeholder="请输入作者"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="开始时间：">
          <el-input v-model="filters.begin_time" placeholder="请输入开始时间"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="search" :icon="Search">搜索</el-button>
        <el-button @click="reset" :icon="Refresh">重置</el-button>
      </el-col>
    </el-row>

    <!-- 按钮部分 deleteSelectedNews-->
    <div class="button-section">
      <el-button type="primary" plain :icon="Plus" @click="openAddDialog">新增</el-button>
      <el-button type="success" plain :icon="Edit" @click="editSelectedMeeting">修改</el-button>
      <el-button type="danger" plain :icon="Delete" @click="deleteSelectedMeeting">删除</el-button>
      <el-button type="warning" plain :icon="Download" @click="exportExcle">导出</el-button>
    </div>

    <!-- 会议列表表格 -->
    <el-table :data="meetingListWithPagination" style="width: 100%" ref="multipleTable"
      @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="会议名称" width="200"></el-table-column>
      <el-table-column prop="creator" label="创建人" width="100"></el-table-column>
      <el-table-column prop="status" label="会议状态" width="100"></el-table-column>
      <!-- <el-table-column prop="content" label="会议内容"></el-table-column> -->
      <el-table-column label="会议内容">
        <template #default="{ row }">
          <el-tooltip class="item custom-tooltip" effect="dark" :content="row.content" placement="top">
            <div style="text-overflow: ellipsis; overflow: hidden; white-space: nowrap; width: 300px;">
              {{ row.content.length > 100 ? row.content.substr(0, 100) + '...' : row.content }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="begin_time" label="开始时间" width="180"></el-table-column>

      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" @click="editMeetings(scope.$index, scope.row)" link size="small"
              :icon="EditPen">修改</el-button>
            <el-button type="primary" @click="deleteMeetings(scope.$index, scope.row)" link size="small"
              :icon="Delete">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination class="pagination-fixed" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pageination.currentPage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="pageination.pageSize"
        layout="total, sizes, prev, pager, next" :total="pageination.total"> <!--  style="text-align: center;" -->
      </el-pagination>
    </div>
    <!-- 添加资讯 -->
    <el-dialog v-model="visible" title="添加资讯" width="70%" @close="resetForm()">
      <div>
        <el-form :model="addFormData" :rules="rules" ref="ruleForm">
          <el-form-item label="会议名称" prop="name" style="width: 500px;">
            <el-input v-model="addFormData.name" placeholder="请输入会议名称"></el-input>
          </el-form-item>
          <el-form-item label="封面图片" prop="image">
            <el-upload class="upload-demo" ref="upload" action="http://localhost:9000/upload"
              :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :file-list="fileList"
              list-type="picture-card" :on-success="handleUploadSuccess" :limit="1" :on-exceed="handleExceed" draggable>

              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item style="margin-top: 0px;">
            <div slot="tip" class="el-upload__tip" style="margin-left: 60px;">文件大小不超过 5MB, 支持 png/jpg/jpeg 格式
            </div>
          </el-form-item>
          <el-dialog v-model="dialogVisible" style="width: 480px; height: auto;">
            <img :src="dialogImageUrl" style="width: 400px; height: auto;" />
          </el-dialog>

          <el-form-item label="会议内容" prop="content">
            <QuillEditorVue ref="quillEditor" :initial-content="addFormData.content"
              @content-updated="handleContentUpdate">
            </QuillEditorVue>

          </el-form-item>
          <el-form-item label="开始时间" prop="begin_time">
            <el-input v-model="addFormData.begin_time" placeholder="请输入开始时间" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="结束时间" prop="end_time">
            <el-input v-model="addFormData.end_time" placeholder="请输入结束时间" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="会议状态" prop="status">
            <el-radio-group v-model="addFormData.status" class="ml-4">
              <el-radio :value="0" size="large">进行中</el-radio>
              <el-radio :value="1" size="large">已结束</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;创建人" prop="creator">
            <el-input v-model="addFormData.creator" placeholder="请输入创建人" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="主办单位" prop="enterprice_name">
            <el-input v-model="addFormData.enterprice_name" placeholder="请输入企业名称" style="width: 200px;"></el-input>
          </el-form-item>

        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false; resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改会议 -->
    <el-dialog v-model="visibleUpdate" title="编辑会议" width="70%" @close="resetForm">
      <div>
        <el-form :model="updateFormData" :rules="rules" ref="ruleForm">
          <el-form-item label="会议名称" prop="name" style="width: 500px;">
            <el-input v-model="updateFormData.name" placeholder="请输入会议名称"></el-input>
          </el-form-item>
          <el-form-item label="封面图片" prop="image">
            <el-upload class="upload-demo" ref="upload1" action="http://localhost:9000/upload"
              :on-preview="handlePreview1" :on-remove="handleRemove1" :before-remove="beforeRemove1"
              :file-list="fileList1" list-type="picture-card" :on-success="handleUploadSuccess1" :limit="1"
              :on-exceed="handleExceed1" draggable>
              <!-- 如果有图片URL，显示图片<el-icon><Plus /></el-icon> -->
              <img v-if="updateFormData.imageURL" :src="updateFormData.imageURL" class="avatar" />

            </el-upload>

          </el-form-item>
          <el-form-item style="margin-top: 0px;">
            <div slot="tip" class="el-upload__tip" style="margin-left: 60px;">文件大小不超过 5MB, 支持 png/jpg/jpeg 格式
            </div>
          </el-form-item>
          <el-dialog v-model="dialogVisible1" style="width: 480px; height: auto;">
            <img :src="dialogImageUrl1" style="width: 400px; height: auto;" />
          </el-dialog>

          <el-form-item label="会议内容" prop="content">
            <QuillEditorVue ref="quillEditor1" :initial-content="updateFormData.content"
              @content-updated="handleContentUpdate1">
            </QuillEditorVue>

          </el-form-item>
          <el-form-item label="开始时间" prop="begin_time">
            <el-input v-model="updateFormData.begin_time" placeholder="请输入开始时间" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="结束时间" prop="end_time">
            <el-input v-model="updateFormData.end_time" placeholder="请输入结束时间" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="会议状态" prop="status">
            <el-radio-group v-model="updateFormData.status" class="ml-4">
              <el-radio :value="0" size="large">进行中</el-radio>
              <el-radio :value="1" size="large">已结束</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;创建人" prop="creator">
            <el-input v-model="updateFormData.creator" placeholder="请输入创建人" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="主办单位" prop="enterprice_name">
            <el-input v-model="updateFormData.enterprice_name" placeholder="请输入企业名称" style="width: 200px;"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visibleUpdate = false; resetForm()">取消</el-button>
          <el-button type="primary" @click="submitEditForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, Ref, onMounted, reactive } from 'vue';
import { Plus, Edit, Delete, Download, EditPen, Search, Refresh } from '../../../node_modules/@element-plus/icons-vue';
import { ElMessage, ElMessageBox, useFormItem } from 'element-plus';
import { type Filters, type MeetingItem, getMeetingList, addMeeting, editMeeting, searchMeetings, deleteMeeting, exportFile } from '../../api/meetingApi.ts'
import QuillEditorVue from '../../components/commonUse/Editor.vue';
import type { UploadProps, UploadUserFile, UploadRawFile, FormInstance } from 'element-plus'
import axios from 'axios';
import { getUserList, type UserItem } from '../../api/userApi.ts';
import { getListCompany, CpyItem, type CompanyItem } from '../../api/companyApi.ts';

const filters: Ref<Filters> = ref({
  name: '',
  creator: '',
  begin_time: ''

});

const meetingList: Ref<MeetingItem[]> = ref([]);
const meetingListWithPagination: Ref<MeetingItem[]> = ref([]);

const fetchMeetings = async () => {
  try {
    meetingList.value = await getMeetingList();
    pageination.total = meetingList.value.length;
    console.log(pageination.total);
    handleCurrentChange(1);
    handleSizeChange(10);

  } catch (error) {

    console.error("获取会议列表失败", error);
  }
};
fetchMeetings();

// 搜索功能
const search = async () => {

  meetingList.value = await searchMeetings(filters.value);
  // handleSizeChange(pageination.pageSize);
  handleCurrentChange(1);
  ElMessage.success('搜索成功！');

};

//重置搜索条件
const reset = () => {
  filters.value = {
    name: '',
    creator: '',
    begin_time: ''
  };
  fetchMeetings();
  ElMessage.success('重置成功！');
};


//添加资讯
const visible = ref(false);

const addFormData = ref<MeetingItem>({
  name: '',
  creator: '',
  content: '',
  imageURL: '',
  status: 0,
  begin_time: '',
  enterprice_name: '',
  end_time: '',
  id: 0
});
const openAddDialog = () => {
  isAddForm.value = true;
  visible.value = true;
  resetForm(); // 打开对话框时重置表单
  fetchMeetings(); // 重新获取数据
};
//图片预览
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const upload = ref(); // 引用上传组件
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url; // 确保设置正确的图片URL
  dialogVisible.value = true;
};
//更新富文本编辑器内容
const quillEditor = ref(null);
const handleContentUpdate = (newContent: string) => {
  addFormData.value.content = newContent;
}

//上传封面图片

const fileList: Ref<UploadRawFile[]> = ref([]);
const handleRemove = (file: any, fileList: any) => {
  //用户点击移除按钮,先执行beforeRemove1中的逻辑，再执行handleRemove1中的逻辑
  addFormData.value.imageURL = fileList.length > 0 ? fileList[0].url : '';
};
const beforeRemove = async (file: any, fileList: any) => {
  try {
    await ElMessageBox.confirm(`确定移除 ${file.name}？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    return true;
  } catch (e) {
    console.error('Remove cancelled', e);
    return false;
  }
};

const handleUploadSuccess = (response: any, file: any, fileList: any) => {
  addFormData.value.imageURL = response.data; // 假设 response.data 是图片 URL
  file.url = response.data; // 更新fileList中的文件URL，确保预览是正确的
};
// 超过文件限制处理函数
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value.clearFiles(); // 清除现有文件
  const newFile = files[0] as UploadRawFile;
  upload.value.handleStart(newFile); // 手动添加文件到上传队列
  fileList.value.push(newFile); // 更新文件列表
};
// 实现提交功能
const submitForm = async () => {
  
  if (ruleForm.value) {
    ruleForm.value.validate(async (valid: any) => {
      console.log("验证结果:", valid);
      if (valid) {
        try {
          await addMeeting(addFormData.value);
          ElMessage.success('提交成功！');
          visible.value = false;
          // 提交后清空表单
          resetForm();
          fetchMeetings();
          isShown.value = false//ELMessage解锁
          isShownCom.value = false
        } catch (error) {
          console.error('Login failed:', error)
          // 可以在这里添加错误处理，例如显示错误消息给用户
        }

      } else {
        ElMessage({
          message: '请提交正确的会议信息!',
          type: 'error',
        });
        return false;
      }
    });
  }
};

//重置表单
const resetForm = async () => {
  addFormData.value = {
    name: '',
    creator: '',
    content: '',
    imageURL: '',
    status: 0,
    begin_time: '',
    enterprice_name: '',
    end_time: '',
    id: 0

  };
  // 清除上传组件的文件列表
  if (upload.value) {
    upload.value.clearFiles();
  }
  // 清除上传组件的文件列表
  if (upload1.value) {
    upload1.value.clearFiles();
  }
  updateFormData.value = {
    name: '',
    creator: '',
    content: '',
    imageURL: '',
    status: 0,
    begin_time: '',
    enterprice_name: '',
    end_time: '',
    id: 0
  };
  if (ruleForm.value) {
    ruleForm.value.resetFields(); // 重置表单字段和验证状态
  }
  isAddForm.value = true;          // 重设为添加模式
  isShown.value = false;           // 重置错误消息显示锁
  isShownCom.value = false;
};

//修改资讯
const visibleUpdate = ref(false);
const updateFormData = ref<MeetingItem>({
  name: '',
  creator: '',
  content: '',
  imageURL: '',
  status: 0,
  begin_time: '',
  enterprice_name: '',
  end_time: '',
  id: 0
});
//更新富文本编辑器内容
const quillEditor1 = ref(null);
const handleContentUpdate1 = (newContent: string) => {
  updateFormData.value.content = newContent;

}
//上传封面图片
const fileList1: Ref<UploadRawFile[]> = ref([]);
//图片预览
const dialogImageUrl1 = ref('');
const dialogVisible1 = ref(false);
const upload1 = ref(); // 引用上传组件
const handlePreview1: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl1.value = uploadFile.url!;
  dialogVisible1.value = true;
};

//删除封面图片
const handleRemove1 = (file: any, fileList: any) => {
  //用户点击移除按钮,先执行beforeRemove1中的逻辑，再执行handleRemove1中的逻辑
  updateFormData.value.imageURL = fileList.length > 0 ? fileList[0].url : '';
};

const beforeRemove1 = async (file: any, fileList: any) => {
  try {
    await ElMessageBox.confirm(`确定移除 ${file.name}？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    return true;
  } catch (e) {
    console.error('Remove cancelled', e);
    return false;
  }
};

const handleUploadSuccess1 = (response: any, file: any, fileList: any) => {
  updateFormData.value.imageURL = response.data; // 假设 response.data 是图片 URL
  file.url = response.data; // 更新fileList中的文件URL
};

const handleExceed1: UploadProps['onExceed'] = (files) => {
  upload1.value.clearFiles(); // 清除现有文件
  const newFile = files[0] as UploadRawFile;
  upload1.value.handleStart(newFile); // 手动添加文件到上传队列
  fileList1.value.push(newFile); // 更新文件列表
};



//编辑
const editMeetings = async (index: number, row: MeetingItem) => {
  resetForm();
  visible.value = false;
  // 确保 Vue 的更新周期完成，确保所有数据被处理
  await nextTick();
  // 使用传入的行数据填充表单
  isAddForm.value = false;
  updateFormData.value = {
    ...row // 展开row对象，并将其值赋给updateFormData
  };

  visibleUpdate.value = true;



};
//提交修改资讯的表单
const submitEditForm = async () => {
  if (ruleForm.value) {
    ruleForm.value.validate(async (valid: any) => {
      console.log("enter")
      if (valid) {
        try {
          await editMeeting(updateFormData.value);
          ElMessage.success('修改成功！');

          visible.value = false;

          // 提交后清空表单
          resetForm();
          visibleUpdate.value = false;
          fetchMeetings();
          isShown.value = false//ELMessage解锁
          isShownCom.value = false
        } catch (error) {
          console.error('Login failed:', error)
          // 可以在这里添加错误处理，例如显示错误消息给用户
        }

      } else {
        ElMessage({
          message: '请提交正确的会议信息!',
          type: 'error',
        });
        return false;
      }
    });
  }


};
//删除资讯
const deleteMeetings = async (index: number, row: MeetingItem) => {
  //获取会议名称
  const name = row.name;
  const id = row.id;
  ElMessageBox.confirm('确定删除该 "' + name + '" 的新闻吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 实现删除功能
    await deleteMeeting(id);
    ElMessage.success('删除成功！');
    fetchMeetings();
  }).catch(() => {
    ElMessage.info('已取消删除');
  });

};
//选择条目功能
//不能实现批量添加，删除，修改，只能对选中的第一条数据进行操作
const selectedRows = ref<MeetingItem[]>([]);
const handleSelectionChange = (selection: MeetingItem[]) => {
  selectedRows.value = selection;
};
const editSelectedMeeting = async () => {
  isAddForm.value = false;
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要编辑的新闻');
    return;
  }
  //选取第一条选中的会议进行编辑
  const row = selectedRows.value[0];
  editMeetings(0, row);
};
const deleteSelectedMeeting = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的新闻');
    return;
  }
  // 遍历选中的所有咨询条目，并逐个执行删除操作
  for (const row of selectedRows.value) {

    const id = row.id;
    try {
      await deleteMeeting(id);

    } catch (error) {
      ElMessage.error('删除失败！');
    }
  }
  ElMessage.success('删除成功！');
  fetchMeetings();
};
//导出excel
const exportExcle = () => {
  exportFile();
  ElMessage.success('导出成功！');
};

//表单验证
const users = ref<UserItem[]>([]);
const isShown = ref(false)//ELMessage解锁(创建者)
const isShownCom = ref(false)//ELMessage解锁(公司)
const companies = ref<CpyItem[]>([]);
onMounted(async () => {
  users.value = await getUserList();
  companies.value = await getListCompany();
});
//表单选择
const isAddForm = ref(true)
// const userNames = ref<String[]>([]);
const ruleForm = ref<FormInstance>()
const rules = {
  name: [
    { required: true, message: '请输入会议名称！', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入会议内容！', trigger: 'blur' }
  ],
  begin_time: [
    { required: true, message: '请输入开始时间！', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 匹配 2024-06-21 或 2024-06-21 16:02:14 格式的正则表达式
        const dateFormat = /^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$/;
        const dateFormat1 = /^\d{4}-\d{2}-\d{2}$/; // YYYY-MM-DD
        const dateFormat2 = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/; // YYYY-MM-DD HH:mm:ss
        if (value === '' || value === undefined || value === null) {
          callback(new Error('请输入开始时间！'));
        } else if (!dateFormat.test(value)) {
          callback(new Error('日期格式不正确，请输入2024-01-01或2024-01-01 00:00:00格式的日期'));
        } else {
          // Check date validity
          if (dateFormat1.test(value)) {
            // YYYY-MM-DD format
            const parts = value.split('-');
            const year = parseInt(parts[0], 10);
            const month = parseInt(parts[1], 10) - 1; // Months are 0-based
            const day = parseInt(parts[2], 10);

            const date = new Date(year, month, day);
            if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
              callback(new Error('输入的日期无效'));
            } else {
              callback();
            }
          } else if (dateFormat2.test(value)) {
            // YYYY-MM-DD HH:mm:ss format
            const datetimeParts = value.split(' ');
            const datePart = datetimeParts[0].split('-');
            const timePart = datetimeParts[1].split(':');

            const year = parseInt(datePart[0], 10);
            const month = parseInt(datePart[1], 10) - 1; // Months are 0-based
            const day = parseInt(datePart[2], 10);
            const hours = parseInt(timePart[0], 10);
            const minutes = parseInt(timePart[1], 10);
            const seconds = parseInt(timePart[2], 10);

            const date = new Date(year, month, day, hours, minutes, seconds);
            if (
              date.getFullYear() !== year ||
              date.getMonth() !== month ||
              date.getDate() !== day ||
              date.getHours() !== hours ||
              date.getMinutes() !== minutes ||
              date.getSeconds() !== seconds
            ) {
              callback(new Error('输入的日期无效'));
            } else {
              callback();
            }
          } else {
            callback(new Error('日期格式不正确，请输入有效的日期'));
          }
        }
      }
    }
  ],
  end_time: [
    { required: true, message: '请输入结束时间！', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 匹配 2024-06-21 或 2024-06-21 16:02:14 格式的正则表达式
        const dateFormat = /^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$/;
        const dateFormat1 = /^\d{4}-\d{2}-\d{2}$/; // YYYY-MM-DD
        const dateFormat2 = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/; // YYYY-MM-DD HH:mm:ss
        if (value === '' || value === undefined || value === null) {
          callback(new Error('请输入开始时间！'));
        } else if (!dateFormat.test(value)) {
          callback(new Error('日期格式不正确，请输入2024-01-01或2024-01-01 00:00:00格式的日期'));
        } else if ((isAddForm.value ? addFormData.value.begin_time : updateFormData.value.begin_time) >= value) {
          callback(new Error('结束时间必须晚于开始时间'));
        } else {
          // Check date validity
          if (dateFormat1.test(value)) {
            // YYYY-MM-DD format
            const parts = value.split('-');
            const year = parseInt(parts[0], 10);
            const month = parseInt(parts[1], 10) - 1; // Months are 0-based
            const day = parseInt(parts[2], 10);

            const date = new Date(year, month, day);
            if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
              callback(new Error('输入的日期无效'));
            } else {
              callback();
            }
          } else if (dateFormat2.test(value)) {
            // YYYY-MM-DD HH:mm:ss format
            const datetimeParts = value.split(' ');
            const datePart = datetimeParts[0].split('-');
            const timePart = datetimeParts[1].split(':');

            const year = parseInt(datePart[0], 10);
            const month = parseInt(datePart[1], 10) - 1; // Months are 0-based
            const day = parseInt(datePart[2], 10);
            const hours = parseInt(timePart[0], 10);
            const minutes = parseInt(timePart[1], 10);
            const seconds = parseInt(timePart[2], 10);

            const date = new Date(year, month, day, hours, minutes, seconds);
            if (
              date.getFullYear() !== year ||
              date.getMonth() !== month ||
              date.getDate() !== day ||
              date.getHours() !== hours ||
              date.getMinutes() !== minutes ||
              date.getSeconds() !== seconds
            ) {
              callback(new Error('输入的日期无效'));
            } else {
              callback();
            }
          } else {
            callback(new Error('日期格式不正确，请输入有效的日期'));
          }
        }
      }
    }
    /* {
      validator: (rule: any, value: any, callback: any) => {
        const beginTime = (isAddForm.value ? addFormData.value.begin_time : updateFormData.value.begin_time);
        const endTime = value;
        const dateFormat1 = /^\d{4}-\d{2}-\d{2}$/;
        const dateFormat2 = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;

        callback();
      }
    } */
  ],
  creator: [
    { required: true, message: '请输入企业创建人！', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        // users.value = await getUserList();
        // console.log(users.value);
        const isGet = ref(false);
        users.value.forEach((user: UserItem) => {
          // console.log("in")
          // console.log('addFormData:'+ addFormData.value.creator)
          // console.log('user:'+user.name)
          if (user.name == value) {
            isGet.value = true;
            // console.log('get')
            callback();
            // console.log("quit")
            return true;
          }
          // console.log("out")
        })
        // console.log("before call")
        callback(new Error('输入的用户未注册'));
        // console.log("before elmessage")
        if (isGet.value == false && isShown.value == false) {
          ElMessage({
            message: '输入的创建人未注册！或者尝试刷新页面',
            type: 'error',
          });
          isShown.value = true;//ELMessage加锁
        }
      }, trigger: 'blur'
    }
  ],
  enterprice_name: [
    { required: true, message: '请输入企业名称！', trigger: 'blur' },
    {
      validator: (rule:any, value:any, callback:any) => {
        // 使用 some() 方法来查找是否有匹配的公司名称
        const companyExists = companies.value.some(company => company.company_name === value);

        if (companyExists) {
          // 如果找到匹配的公司，验证通过
          callback();
        } else {
          // 如果未找到，验证不通过，并提供错误信息
          console.log("输入的租户未注册！");
          if (!isShownCom.value) {
            ElMessage.error('输入的租户未注册！或者尝试刷新页面');
            isShownCom.value = true; // 设置锁，防止消息重复显示
          }
          callback(new Error('输入的租户未注册'));
        }
      },
      trigger: 'blur'
    }
  ]
};


//分页
const pageination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 64
});
//当每页条数发生了变化，调用此函数
const handleSizeChange = (val: number) => {
  pageination.pageSize = val;
  meetingListWithPagination.value = meetingList.value.slice((pageination.currentPage - 1) * pageination.pageSize, Math.min((pageination.currentPage) * pageination.pageSize, pageination.total));
};
//当前页码发生变化，调用此函数
const handleCurrentChange = (val: number) => {
  pageination.currentPage = val;
  meetingListWithPagination.value = meetingList.value.slice((pageination.currentPage - 1) * pageination.pageSize, Math.min((pageination.currentPage) * pageination.pageSize, pageination.total));
};
</script>

<style scoped>
.course {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 1200px;
  padding: 20px;
  margin: 0 auto;
}

.search-section {
  margin-bottom: 0px;
  width: 100%;
}

.button-section {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
}

.upload-demo .el-upload__tip {
  font-size: 12px;
  line-height: 1.0;
  margin-top: 0px;
}

.avatar-uploader-icon {
  border: 1px dashed var(--el-border-color);
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 158px;
  text-align: center;
}

.avatar {
  width: 100%;
  /* 根据需要调整尺寸 */
  height: auto;
  cursor: pointer;
}

.pagination-fixed {
  text-align: center;
}

.pagination-container {
  /* position: fixed; */
  display: flex;
  margin-top: 25px;
  /* margin-bottom: -2000px; */
  justify-content: center;
  width: 100%;
  z-index: 1000;
  /* 确保分页条在最上层 */
}

.custom-tooltip .el-tooltip__popper {
  max-width: 400px;
  /* 限制最大宽度为 200px */
}
</style>
